package edu.webtech.project.server;

import java.io.IOException;
import java.util.Map;

import javax.jdo.PersistenceManager;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.google.appengine.api.blobstore.BlobKey;
import com.google.appengine.api.blobstore.BlobstoreService;
import com.google.appengine.api.blobstore.BlobstoreServiceFactory;

import edu.webtech.project.server.domain.FileData;

@SuppressWarnings("serial")
public class HandleUpload extends HttpServlet {
	BlobstoreService blobstoreService = BlobstoreServiceFactory.getBlobstoreService();
	
	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		@SuppressWarnings("deprecation")
		Map<String, BlobKey> blobs = blobstoreService.getUploadedBlobs(request);
		BlobKey blobKey = blobs.get("upload");
		
		PersistenceManager pm = PMF.get().getPersistenceManager();
		try {

		// Get parameters from request and populate our FileData
		FileData file = new FileData();
		file.setFileName(request.getParameter("fileName"));
		file.setSemesterName(request.getParameter("semesterName"));
		file.setCourseName(request.getParameter("courseName"));
		file.setSubjectName("Webtech");
		
		// The URL that will be used to access the file
		file.setUrl("/webtechproject/fileService?blob-key=" + blobKey.getKeyString());
		
		// insert it into the DataStore
		pm.makePersistent(file);
		
		} 
		catch (Exception e) {
			e.printStackTrace();
		} finally {
			pm.close();
		}
	}
}
